<?php

use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use App\Models\Menu;
use App\Models\Org;
use App\Models\AppSetting;
use App\Models\WebsiteSetting;
use \Illuminate\Support\Facades\Log;
use UCloud\USMS\Apis\SendUSMSMessageRequest;
use UCloud\USMS\USMSClient;

/**
 * 发送登录验证码
 * @param $mobile
 * @param $code
 * @return bool
 */
//function send_sms_login($mobile, $code) {
//    $sendSmsRequest = new SendSmsRequest([
//        "phoneNumbers" => $mobile,
//        'templateCode' => 'SMS_187942935',
//        'templateParam' => json_encode(['code' => $code]),
//        "signName" => "dkonline"
//    ]);
//    try {
//        $response = \App\Facades\Sms::sendSms($sendSmsRequest);
//        if ($response->statusCode==200 && $response->body->code == 'OK') return true;
//    } catch (\Exception $e) {
//        Log::warning(sprint("fail send sms code to %s", $mobile), $e);
//    }
//
//    return false;
//}

//
//function send_sms_login($telephone,$sms_code)
//{
//    try {
//        $client = new USMSClient([
//            "publicKey" => "4eZCGoHHvvz54rxKeinwG2DXu0jmYiS8R",
//            "privateKey" => "6KZhaAGDpiK4suL9aSwpb48ozEgr4FSWH2kqBFIwbhkM",
//            "projectId" => "org-4zlg4g",
//            "log_level"=>'WARNING'
//        ]);
//        $req = new SendUSMSMessageRequest();
//
//        $req->setPhoneNumbers([$telephone]);
//
//        $req->setSigContent("SIG202501101FD2A3");
//        $req->setTemplateId("UTA250421R1EIZK");
//        $req->setTemplateParams([$sms_code]);
//        $resp = $client->sendUSMSMessage($req);
//        return $resp->toArray();
//    } catch (\UCloud\Core\Exception\UCloudException $e) {
//        throw $e;
//    }
//
//}

function send_sms_login($telephone,$sms_code)
{
//    try {
//        $client = new USMSClient([
//            "publicKey" => "4eZCGoHHvvz54rxKeinwG2DXu0jmYiS8R",
//            "privateKey" => "6KZhaAGDpiK4suL9aSwpb48ozEgr4FSWH2kqBFIwbhkM",
//            "projectId" => "org-4zlg4g",
//        ]);
//        $req = new SendUSMSMessageRequest();
//        $req->setPhoneNumbers([$telephone]);
//        $req->setSigContent("SIG202501101FD2A3");
//        $req->setTemplateId("UTA250421R1EIZK");
//        $req->setTemplateParams([$sms_code]);
//        $resp = $client->sendUSMSMessage($req);
//        return $resp->toArray();
//    } catch (\UCloud\Core\Exception\UCloudException $e) {
//        throw $e;
//    }


    $url = 'http://text.rongyuejinfu.com/admin/text_message/get_code';
    $ch = curl_init($url);
    // 设置cURL选项
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // 设置请求类型为POST
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['phone'=>$telephone,'sms_code'=>$sms_code],true)); // 发送JSON数据  JSON_UNESCAPED_UNICODE
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应，而不是直接输出
    curl_setopt($ch, CURLOPT_HTTPHEADER, array( // 设置HTTP头部
        'Content-Type: application/json', // 设置内容类型为JSON
        'Content-Length: ' . strlen(json_encode(['phone'=>$telephone,'sms_code'=>$sms_code])) // 设置内容长度
    ));
    // 执行cURL会话
    $response = curl_exec($ch);
    // 获取错误信息
    $error = curl_error($ch);
    // 关闭cURL会话
    curl_close($ch);
    return $response;
}




/**
 * @return void
 */
function build_tree($row, $parentId=0) {
    $branch = array();
    foreach ($row as $element) {
        if ($element['pid'] == $parentId) {
            $children = build_tree($row, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }

    return $branch;
}

/**
 * 创建下级机构码
 *
 * @param $org_code 父机构号
 * @param $sub_len 子机构位数
 * @return string
 * @throws Exception
 */
function createSubOrgcode($org_code, $sub_len = 2) {

    $len = strlen($org_code);
    $codes = \App\Models\Org::where("org_code", "like", "{$org_code}%")
        ->whereRaw("LENGTH(org_code) = ? ", $len + $sub_len)
        ->select("org_code")
        ->get();
    // 判断当前最大的code 36进制
    $max_code = 0;

    foreach ($codes as $v) {
       $codeInt = (int) base_convert(substr($v->org_code, $len), 36, 10);
       if($codeInt > $max_code) $max_code = $codeInt;
    }

    if ($max_code >= 36 * 36 - 1) {
        throw  new \Exception("org code to large: large than 36 * 36 = 1296 ");
    }

    $code = base_convert($max_code+1, 10, 36);
    return sprintf("%s%02s", substr($org_code, 0, $len), strtoupper($code));
}

/**
 * 获取指定机构的菜单
 * @param $org_code
 * @return array
 */
function getOrgMenu($org_code) {
    $org = Org::where('org_code',$org_code)->first();
    if($org) {
        $menu =  $org->menus->makeHidden(['pivot','created_at','updated_at'])->toArray();
    } else {
        $menu = [];
    }
    return $menu;
}


/**
 * 获取用户菜单
 * @param \App\Models\User $user
 * @return array
 */
function getUserMenu(\App\Models\User $user) {
    if ($user->isSupper()) return Menu::all()->makeHidden(['created_at','updated_at']);

    $org = Org::where('org_code',$user->org_code)->first();
    if($org) {
        $menu =  $org->menus->makeHidden(['pivot','created_at','updated_at'])->toArray();
    } else {
        $menu = [];
    }
    return $menu;
}

/**
 * 获取当前机构及子机构
 * @param \App\Models\User $user
 * @return array|null
 */
function getOrgTree(\App\Models\User $user) {
    return  build_tree(Org::ofOrgCode($user)->get()->toArray(), $user->org->pid);
}




function getCityTree() {
    return  build_tree(\App\Models\WebsiteCity::get()->toArray());
}

/**
 * 将 "1万 - 3万" 这样的数字转化成 [10000, 30000]， "xxx 以上变成 [xxx, 10 * 12]"
 * @param $amount
 * @return array|int[]|void
 */
function parseAmount($amount) {
    $str = str_replace(["-", "，", "—"],",", trim($amount));
    $str = str_replace(" ","", $str);

    $arr = explode(",", $str);
    if (count($arr) >= 2) {
        return [parseZhNum($arr[0]), parseZhNum($arr[1])];
    } else if (count($arr) == 1)  {
        if (str_ends_with($amount, "以上")) {
            return [parseZhNum($arr[0]), 10 * 12];
        } else {
            return [parseZhNum($arr[0]), parseZhNum($arr[0])];
        }
    }  else if (count($arr) == 0)  {
        return [0, 0];
    }
}

/**
 * 将中文数字百千万单位换算成整型
 * 如 1万1千 => 11000, 10万 => 10000
 * @return int
 */
function parseZhNum($zh_num) {
    if (preg_match('/^-?(?:\d+|\d*\.\d+)$/', $zh_num)) {
        return floatval($zh_num);
    }

    $zh_num = str_replace("万亿","L", (string) $zh_num);
    $zh_num = str_replace("千亿","K", (string) $zh_num);
    $zh_num = str_replace("百亿","J", (string) $zh_num);
    $zh_num = str_replace("十亿","I", (string) $zh_num);
    $zh_num = str_replace("亿","H", (string) $zh_num);
    $zh_num = str_replace("千万","G", (string) $zh_num);
    $zh_num = str_replace("百万","F", (string) $zh_num);
    $zh_num = str_replace("十万","E", (string) $zh_num);
    $zh_num = str_replace("万","D", (string) $zh_num);
    $zh_num = str_replace("千","C", (string) $zh_num);
    $zh_num = str_replace("百","B", (string) $zh_num);
    $str = str_replace("十","A", (string) $zh_num);


    $pre = '';
    $num = 0;
    foreach (str_split($str) as $v) {
        if (!in_array( $v, str_split("ABCDEFJHIJKL"))) {
            $pre .= $v;
        } else {
            $pow = ord($v)  - ord('A') + 1;
            $num += floatval($pre) * (10 ** $pow);
            $pre = '';
        }
    }

    return $num;
}

/**
 * 转换成易读数字
 *
 * @param $num
 * @return string
 */
function toZhNum($num) {
    if ($num == 0) return  (string) $num;

    if ($num % (10 ** 8) == 0) {
        return sprintf("%s亿",  $num / (10 ** 8));
    }

    if ($num % (10 ** 4) == 0) {
        return sprintf("%s万",  $num / (10 ** 4));
    }

    if ($num % (10 ** 3) == 0) {
        return sprintf("%s千",  $num / (10 ** 3));
    }

    return  (string) $num;
}

/**
 * 贷款类别
 *
 * @return string[]
 */
function loan_catetory() {
    return ['general', 'credit-provident', 'mortgage-car', 'mortgage-house', 'mortgage-tax'];
}


/**
 * @param $key
 * @return bool|mixed[]|null
 */
function app_setting($key) {
    if ($key === null) {
        return AppSetting::all()->pluck('value', 'key')->toArray();
    }

    if (is_array($key)) {
        foreach ($key as $k => $v) {
            $model = AppSetting::where('key', $k)->first();
            if(empty($model)) {
                $model = new AppSetting();
                $model->key = $k;
            }
            $model->value = $v;
            $model->save();
        }

        return true;
    }

    $model = AppSetting::where('key', $key)->first();
    if (!$model) return null;
    return $model->value;
}
/**
 * @param $key
 * @return bool|mixed[]|null
 */
function web_setting($key) {
    if ($key === null) {
        return WebsiteSetting::all()->pluck('value', 'key')->toArray();
    }

    if (is_array($key)) {
        foreach ($key as $k => $v) {
            $model = WebsiteSetting::where('key', $k)->first();
            if(empty($model)) {
                $model = new WebsiteSetting();
                $model->key = $k;
            }
            $model->value = $v;
            $model->save();
        }

        return true;
    }

    $model = AppSetting::where('key', $key)->first();
    if (!$model) return null;
    return $model->value;
}
